<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
<!-- exceptionsafety.qdoc -->
  <title>Exception Safety | Qt 5.14</title>
  <link rel="stylesheet" type="text/css" href="style/offline-simple.css" />
  <script type="text/javascript">
    document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");
    // loading style sheet breaks anchors that were jumped to before
    // so force jumping to anchor again
    setTimeout(function() {
        var anchor = location.hash;
        // need to jump to different anchor first (e.g. none)
        location.hash = "#";
        setTimeout(function() {
            location.hash = anchor;
        }, 0);
    }, 0);
  </script>
</head>
<body>
<div class="header" id="qtdocheader">
  <div class="main">
    <div class="main-rounded">
      <div class="navigationbar">
        <table><tr>
<td ><a href="index.html">Qt 5.14</a></td><td >Exception Safety</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right">Qt 5.14.2 Reference Documentation</td>
        </tr></table>
      </div>
    </div>
<div class="content">
<div class="line">
<div class="content mainContent">
<div class="sidebar">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#exception-safe-modules">Exception Safe Modules</a></li>
<li class="level2"><a href="#containers">Containers</a></li>
<li class="level1"><a href="#out-of-memory-handling">Out of Memory Handling</a></li>
<li class="level1"><a href="#recovering-from-exceptions">Recovering from Exceptions</a></li>
<li class="level1"><a href="#exceptions-in-client-code">Exceptions in Client Code</a></li>
<li class="level2"><a href="#signals-and-slots">Signals and Slots</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">Exception Safety</h1>
<span class="subtitle"></span>
<!-- $$$exceptionsafety.html-description -->
<div class="descr"> <a name="details"></a>
<p><b>Preliminary warning</b>: Exception safety is not feature complete! Common cases should work, but classes might still leak or even crash.</p>
<p>Qt itself will not throw exceptions. Instead, error codes are used. In addition, some classes have user visible error messages, for example <a href="../qtcore/qiodevice.html#errorString">QIODevice::errorString</a>() or <a href="../qtsql/qsqlquery.html#lastError">QSqlQuery::lastError</a>(). This has historical and practical reasons - turning on exceptions can increase the library size by over 20%.</p>
<p>The following sections describe Qt's behavior if exception support is enabled at compile time.</p>
<a name="exception-safe-modules"></a>
<h2 id="exception-safe-modules">Exception Safe Modules</h2>
<a name="containers"></a>
<h3 id="containers">Containers</h3>
<p>Qt's <a href="topics-core.html#container-classes">container classes</a> are generally exception neutral. They pass any exception that happens within their contained type <code>T</code> to the user while keeping their internal state valid.</p>
<p>Example:</p>
<pre class="cpp">

  <span class="type"><a href="../qtcore/qlist.html">QList</a></span><span class="operator">&lt;</span><span class="type"><a href="../qtcore/qstring.html">QString</a></span><span class="operator">&gt;</span> list;
  <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span>
  <span class="keyword">try</span> {
      list<span class="operator">.</span>append(<span class="string">&quot;hello&quot;</span>);
  } <span class="keyword">catch</span> (<span class="operator">.</span><span class="operator">.</span><span class="operator">.</span>) {
  }
  <span class="comment">// list is safe to use - the exception did not affect it.</span>

</pre>
<p>Exceptions to that rule are containers for types that can throw during assignment or copy constructions. For those types, functions that modify the container as well as returning a value, are unsafe to use:</p>
<pre class="cpp">

  MyType s <span class="operator">=</span> list<span class="operator">.</span>takeAt(<span class="number">2</span>);

</pre>
<p>If an exception occurs during the assignment of <code>s</code>, the value at index 2 is already removed from the container, but hasn't been assigned to <code>s</code> yet. It is lost without chance of recovery.</p>
<p>The correct way to write it:</p>
<pre class="cpp">

  MyType s <span class="operator">=</span> list<span class="operator">.</span>at(<span class="number">2</span>);
  list<span class="operator">.</span>removeAt(<span class="number">2</span>);

</pre>
<p>If the assignment throws, the container will still contain the value; no data loss occurred.</p>
<p>Note that implicitly shared Qt classes will not throw in their assignment operators or copy constructors, so the limitation above does not apply.</p>
<a name="out-of-memory-handling"></a>
<h2 id="out-of-memory-handling">Out of Memory Handling</h2>
<p>Most desktop operating systems overcommit memory. This means that <code>malloc()</code> or <code>operator new</code> return a valid pointer, even though there is not enough memory available at allocation time. On such systems, no exception of type <code>std::bad_alloc</code> is thrown.</p>
<p>On all other operating systems, Qt will throw an exception of type std::bad_alloc if any allocation fails. Allocations can fail if the system runs out of memory or doesn't have enough continuous memory to allocate the requested size.</p>
<p>Exceptions to that rule are documented. As an example, <a href="../qtgui/qimage.html">QImage</a> constructors will create a <a href="../qtgui/qimage.html#isNull">null</a> image if not enough memory exists instead of throwing an exception.</p>
<a name="recovering-from-exceptions"></a>
<h2 id="recovering-from-exceptions">Recovering from Exceptions</h2>
<p>Currently, the only supported use case for recovering from exceptions thrown within Qt (for example due to out of memory) is to exit the event loop and do some cleanup before exiting the application.</p>
<p>Typical use case:</p>
<pre class="cpp">

  <span class="type"><a href="../qtwidgets/qapplication.html">QApplication</a></span> app(argc<span class="operator">,</span> argv);
  <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span>
  <span class="type">int</span> ret;
  <span class="keyword">try</span> {
      ret <span class="operator">=</span> app<span class="operator">.</span>exec();
  } <span class="keyword">catch</span> (<span class="keyword">const</span> std<span class="operator">::</span>bad_alloc <span class="operator">&amp;</span>) {
      <span class="comment">// clean up here, e.g. save the session</span>
      <span class="comment">// and close all config files.</span>

      <span class="keyword">return</span> EXIT_FAILURE; <span class="comment">// exit the application</span>
  }
  <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span>
  <span class="keyword">return</span> ret;

</pre>
<p>After an exception is thrown, the connection to the windowing server might already be closed. It is not safe to call a GUI related function after catching an exception.</p>
<a name="exceptions-in-client-code"></a>
<h2 id="exceptions-in-client-code">Exceptions in Client Code</h2>
<a name="signals-and-slots"></a>
<h3 id="signals-and-slots">Signals and Slots</h3>
<p>Throwing an exception from a slot invoked by Qt's <a href="../qtcore/signalsandslots.html">signal-slot</a> connection mechanism is considered undefined behaviour, unless it is handled within the slot:</p>
<pre class="cpp">

  State state;
  StateListener stateListener;

  <span class="comment">// OK; the exception is handled before it leaves the slot.</span>
  <span class="type"><a href="../qtcore/qobject.html">QObject</a></span><span class="operator">::</span>connect(<span class="operator">&amp;</span>state<span class="operator">,</span> SIGNAL(stateChanged())<span class="operator">,</span> <span class="operator">&amp;</span>stateListener<span class="operator">,</span> SLOT(throwHandledException()));
  <span class="comment">// Undefined behaviour; upon invocation of the slot, the exception will be propagated to the</span>
  <span class="comment">// point of emission, unwinding the stack of the Qt code (which is not guaranteed to be exception safe).</span>
  <span class="type"><a href="../qtcore/qobject.html">QObject</a></span><span class="operator">::</span>connect(<span class="operator">&amp;</span>state<span class="operator">,</span> SIGNAL(stateChanged())<span class="operator">,</span> <span class="operator">&amp;</span>stateListener<span class="operator">,</span> SLOT(throwUnhandledException()));

</pre>
<p>If the slot was invoked directly, like a regular function call, exceptions may be used. This is because the connection mechanism is bypassed when invoking slots directly:</p>
<pre class="cpp">

  State state;
  StateListener stateListener;

  <span class="comment">// ...</span>

  <span class="keyword">try</span> {
      <span class="comment">// OK; invoking slot directly.</span>
      stateListener<span class="operator">.</span>throwException();
  } <span class="keyword">catch</span> (<span class="operator">.</span><span class="operator">.</span><span class="operator">.</span>) {
      <a href="../qtcore/qtglobal.html#qDebug">qDebug</a>() <span class="operator">&lt;</span><span class="operator">&lt;</span> <span class="string">&quot;Handling exception not caught in slot.&quot;</span>;
  }

</pre>
</div>
<!-- @@@exceptionsafety.html -->
        </div>
       </div>
   </div>
   </div>
</div>
<div class="footer">
   <p>
   <acronym title="Copyright">&copy;</acronym> 2020 The Qt Company Ltd.
   Documentation contributions included herein are the copyrights of
   their respective owners.<br/>    The documentation provided herein is licensed under the terms of the    <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation    License version 1.3</a> as published by the Free Software Foundation.<br/>    Qt and respective logos are trademarks of The Qt Company Ltd.     in Finland and/or other countries worldwide. All other trademarks are property
   of their respective owners. </p>
</div>
</body>
</html>
